Find common characters¶
Time: O(NxL); Space: O(1); easy
Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
Example 1:
Input: A = [“bella”,“label”,“roller”]
Output: [“e”,“l”,“l”]
Example 1:
Input: A = [“cool”,“lock”,“cook”]
Output: [“c”,“o”]
Notes:
1 <= len(A) <= 100
1 <= len(A[i]) <= 100
A[i][j] is a lowercase letter
[1]:
import collections
class Solution1(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
result = collections.Counter(A[0])
for a in A:
result &= collections.Counter(a)
return list(result.elements())
[3]:
s = Solution1()
A = ["bella", "label", "roller"]
assert s.commonChars(A) == ["e", "l", "l"]
A = ["cool", "lock", "cook"]
assert s.commonChars(A) == ["c", "o"]